﻿@model OnlineEducation.Data.Entities.Course
@{
    List<OnlineEducation.Data.Entities.Code> subjects = ViewBag.Subjects as List<OnlineEducation.Data.Entities.Code>;
}


@section Styles{

    <link href="~/assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css" />
    <!-- Summernote css -->
    <link href="~/assets/libs/summernote/summernote-bs4.css" rel="stylesheet" type="text/css" />

    <!-- Plugins css -->
    <link href="~/assets/libs/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
    <link href="~/assets/libs/dropify/dropify.min.css" rel="stylesheet" type="text/css" />

    <style>
        @@media (min-width: 576px) {
            .modal-dialog {
                max-width: 729px;
                margin: 1.75rem auto;
            }
        }

        .tab-content {
            padding: 0 0 0 0;
        }

        hr {
            border-top: 1px solid #ced4da;
        }
    </style>
}

<!-- Start Content-->
<div class="container-fluid">

    <!-- start page title -->
    <div class="row">
        <div class="col-12">
            <div class="page-title-box">
                <div class="page-title-right">

                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="javascript: void(0);"><i class="fa fa-map-marker-alt"></i></a></li>
                        <li class="breadcrumb-item"><a href="javascript: void(0);">课程</a></li>
                        <li class="breadcrumb-item active">添加</li>
                    </ol>
                </div>
                <h4 class="page-title">添加课程</h4>
            </div>
        </div>
    </div>
    <!-- end page title -->


    <div class="row">

        <div class="col-12">

            <div class="card-box mb-0">

                <p class="card-text"></p>
                <p class="card-text">
                    添加课程包括2个部分，添加课程基本信息和添加课时信息。每个课时对应每一节课，具体的每一课时的开始时间在教学计划里设定。一个课程可设定多个教学计划。
                </p>

                <div id="coursewizard" class="pb-3 pt-0 pl-3 pr-3">

                    <ul class="nav nav-pills bg-light nav-justified form-wizard-header mb-4">
                        <li class="nav-item">
                            <a href="#tab-course" data-toggle="tab" id="tab-header-course" class="nav-link rounded-0 pt-2 pb-2 active" onclick="showCourseBtn()">
                                <i class="mdi mdi-book-open-page-variant mr-1"></i>
                                <span class="d-none d-sm-inline">添加课程基本信息</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="#tab-lesson" data-toggle="tab" id="tab-header-lesson" class="nav-link rounded-0 pt-2 pb-2" onclick="showLessonBtn()">
                                <i class="mdi mdi-av-timer mr-1"></i>
                                <span class="d-none d-sm-inline">添加课时信息</span>
                            </a>
                        </li>

                    </ul>

                    <div class="tab-content b-0 mb-0">

                        <div class="tab-pane active" id="tab-course">
                            <form id="courseForm" class="form-horizontal">
                                <div class="row">

                                    <div class="col-12">
                                        <input type="hidden" id="courseid" asp-for="Id" value="@Model.Id" />
                                        <input type="hidden" asp-for="TeacherId" />

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="Subject"><span class="text-danger">*</span>科目</label>
                                            <div class="col-md-8">
                                                <select asp-for="SubjectCode" class="form-control select2 m-1" asp-items="OnlineEducation.Constants.CodeHelper.GetListItems(subjects)"></select>
                                                <span asp-validation-for="SubjectCode" class="text-danger"></span>

                                            </div>
                                            <div class="col-md-2">
                                                <a target="_blank" href='/Subject/Index' class="btn btn-outline-secondary  waves-effect waves-light float-left ladda-button" data-style="expand-left">
                                                    新增科目
                                                </a>
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label pull-right" for="Title"><span class="text-danger">*</span>标题</label>
                                            <div class="col-md-10">
                                                <input asp-for="Title" type="text" class="form-control" placeholder="输入课程标题" />
                                                <span asp-validation-for="Title" class="text-danger"></span>
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="course-subtitle">副标题</label>
                                            <div class="col-md-10">
                                                <input asp-for="SubTitle" type="text" class="form-control" placeholder="输入课程副标题" />
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="course-description">课程描述</label>
                                            <div class="col-md-10">
                                                <textarea asp-for="Description" class="form-control" rows="6"></textarea>
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="course-cover">封面</label>
                                            <input type="hidden" id="course-coverpictureurl" />
                                            <div class="col-md-10">
                                                <input type="file" class="dropify" id="CoverPictureURL" name="CoverPictureURL" data-height="100" data-allowed-file-extensions="jpg png jpeg" data-max-file-size-preview="3M" data-default-file="@Model.CoverPictureURL" />
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="confirm">标签</label>
                                            <div class="col-md-10">
                                                <input asp-for="Tag" type="text" class="form-control" placeholder="输入标签，多个以逗号分隔" />
                                            </div>
                                        </div>

                                        <div class="form-group row mb-3">
                                            <label class="col-md-2 col-form-label" for="course-price">价格</label>
                                            <div class="col-md-10">
                                                <input asp-for="Price" type="text" class="form-control" placeholder="输入价格" />
                                            </div>
                                        </div>



                                    </div> <!-- end col -->
                                </div> <!-- end row -->
                            </form>
                            <hr />
                            <div class="row mt-3">
                                <div class="col-12">
                                    <div class="text-right">
                                        <a href="javascript:void(0)" id="btnSaveNext" class="btn btn-primary">保存并继续</a>
                                        @*<button type="button" id="btnReset" class="btn w-sm btn-secondary  waves-effect">重置</button>*@
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="tab-pane" id="tab-lesson">
                            <div class="row">
                                <div class="col-12">

                                    <button onclick="ShowPopup('/Course/Lesson/Add?courseId='+$('#courseid').val())" class="btn btn-outline-primary  waves-effect waves-light float-right ladda-button" data-style="expand-left">
                                        新增课时
                                    </button>

                                    <h4 class="header-title mb-4">课时列表</h4>

                                    <table class="table table-hover m-0 table-centered dt-responsive nowrap w-100" id="datatable">
                                        <thead>
                                            <tr>
                                                <th width="10%">序号</th>
                                                <th width="10%">章-节</th>
                                                <th width="10%">标题</th>
                                                <th width="10%">时长</th>
                                                <th width="10%">课件</th>
                                                <th class="hidden-sm"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div> <!-- end col -->
                            </div> <!-- end row -->
                            <hr />
                            <div class="row mt-1">
                                <div class="col-12">

                                    <div class="text-right">
                                        <button type="button" id="btnSubmit" class="btn w-sm btn-primary waves-effect waves-light">发布课程</button>
                                        @*<button type="button" id="btnReset" class="btn w-sm btn-secondary  waves-effect">重置</button>*@
                                    </div>
                                </div>
                            </div>

                        </div>



                    </div> <!-- tab-content -->
                </div> <!-- end #coursewizard-->


            </div> <!-- end col-->

        </div> <!-- end col-->
        <!-- end row -->
        <div class="row">

        </div>
        <!-- end row -->


    </div> <!-- container -->
</div>
<div id="modalDefault" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">

        </div>
    </div>
</div><!-- /.modal -->

@section Scripts{
    @await Html.PartialAsync("_ValidationScriptsPartial")
    <!-- Plugins js-->
    <script src="~/assets/libs/moment/moment.min.js"></script>
    <script src="~/assets/libs/flatpickr/flatpickr.min.js"></script>
    <script src="~/assets/libs/flatpickr/zh.js"></script>
    <script src="~/assets/libs/twitter-bootstrap-wizard/jquery.bootstrap.wizard.min.js"></script>
    <!-- Summernote js -->
    <script src="~/assets/libs/summernote/summernote-bs4.min.js"></script>
    <script src="~/assets/libs/summernote/summernote-zh-CN.min.js"></script>


    <!-- Plugins js -->
    <script src="~/assets/libs/dropzone/dropzone.min.js"></script>
    <script src="~/assets/libs/dropify/dropify.min.js"></script>


    <script>

        var table;
        $(function () {


            $('.select2').select2({width:'100%'});

            $("#course-start-time").flatpickr({ enableTime: false, dateFormat: "Y-m-d", locale: "zh" });

            $("#lesson-start-time").flatpickr({ enableTime: true, noCalendar: true, dateFormat: "H:i", locale: "zh" });

            $("#coursewizard").bootstrapWizard({
                onNext: function (tab, navigation, index) {
                    console.log(tab);
                    var form = $("#courseForm");
                    form.removeData('validator');
                    form.removeData('unobtrusiveValidation');
                    $.validator.unobtrusive.parse(form);
                    return form.valid();
                    //var o = $($(tab).data("targetForm"));
                    //if (o && (o.addClass("was-validated"),false === o[0].checkValidity()))
                    //return event.preventDefault(), event.stopPropagation(),false
                }
            })

            //$("#Description").summernote({
            //    lang: 'zh-CN',
            //    placeholder: '输入课程描述',
            //    height: 100,
            //    minHeight: null,
            //    maxHeight: 150,
            //    focus: false
            //});

            $(".dropify").dropify({
                messages: {
                    default: "拖放一个文件到这里或者点击添加一个文件",
                    replace: "拖放或者点击替换一个文件",
                    remove: "删除",
                    error: "Ooops, 出错了."
                },
                error: {
                    fileSize: "文件尺寸太大 (最大3M).",
                    imageFormat: '只允许({{ value }})文件格式.'
                }
            });

            table = $('#datatable').DataTable({
                "oLanguage": {
                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                    "sZeroRecords": "对不起，没有匹配的数据",
                    "sInfo": "第 _START_ - _END_ 条 / 共 _TOTAL_ 条数据",
                    "sInfoEmpty": "没有匹配的数据",
                    "sInfoFiltered": "(数据表中共 _MAX_ 条记录)",
                    "sProcessing": "正在加载中...",
                    "sSearch": "全文搜索：",
                    "oPaginate": {
                        "sFirst": "第一页",
                        "sPrevious": " 上一页 ",
                        "sNext": " 下一页 ",
                        "sLast": " 最后一页 "
                    }
                },
                language: {
                    paginate:
                        { previous: "<i class='mdi mdi-chevron-left'>", next: "<i class='mdi mdi-chevron-right'>" }
                },
                drawCallback: function () { $(".dataTables_paginate > .pagination").addClass("pagination-rounded") },

                "responsive": true,
                "lengthChange": true,
                "searching": false,
                "paging": false,
                "order": [[0, 'asc']],
                "aoColumnDefs": [{ "bSortable": false, "aTargets": [1, 2, 3, 4] }],
                "serverSide": true,
                ajax: {
                    url: '/Course/Lessons',
                    type: 'POST',
                    async: true,
                    //headers: {
                    //    "XSRF-TOKEN": document.querySelector('[name="__RequestVerificationToken"]').value
                    //},
                    data: function (data) {
                        data.AdditionalValues = [$("#courseid").val()];
                        return {
                            param: data

                        };
                    },
                    error: function (jqXHR) {
                        HandleGlobalException(jqXHR);
                    }
                },

                columns: [
                    {
                        title: "序号",
                        data: "Sequence",
                        name: "Sequence",

                    },
                    {
                        title: "章-节",
                        data: "PhoneNumber",
                        name: "PhoneNumber",
                        render: function (data, type, row) {

                            return row["Chapter"] + '-' + row["Section"];
                        }
                    },
                    {
                        title: "标题",
                        data: "Title",
                        name: "Title"
                    },
                    {
                        title: "时长(分钟)",
                        data: "Duration",
                        name: "Duration"
                    },

                    {
                        title: "课件",
                        render: function (data, type, row) {
                            return "<a target='_blank' href='" + row["MaterialURLs"] + "'>打开</a>";
                        }
                    },
                    {
                        title: "",
                        data: null,
                        name: null,
                        render: function (data, type, row) {

                            var html = "<div class='btn-group dropdown'>" +
                                "<a href='javascript: void(0);' class='table-action-btn dropdown-toggle arrow-none btn btn-outline-secondary waves-effect btn-sm' data-toggle='dropdown' aria-expanded='false'><i class='ti-menu'></i></a>" +
                                "<div class='dropdown-menu dropdown-menu-left'>" +
                                "<a class='dropdown-item' href='#' onclick='ShowPopup(\"/Course/Lesson/" + row["Id"] + "\")'><i class='mdi mdi-pencil mr-2 text-muted font-18 vertical-middle'></i>查看</a>";


                            html = html + "<a class='dropdown-item' href='#' onclick='ShowPopup(\"/Course/Lesson/Edit/" + row["Id"] + "\")'><i class='mdi mdi-check mr-2 text-muted font-18 vertical-middle'></i>修改</a>";
                            html = html + "<a class='dropdown-item' href='#' onclick='RemoveLesson(\"" + row["Id"] + "\")'><i class='mdi mdi-delete-forever mr-2 text-muted font-18 vertical-middle'></i>删除</a></div></div>";

                            return html;

                        }
                    }

                ]


            });

            $("#btnSaveNext").click(function () {
                var form = $("#courseForm");
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);

                if (form.valid()) {
                    var data = new FormData(form[0]);

                    data.Id = $("#courseId").val();

                    $.ajax({
                        type: 'POST',
                        url: '/Course/Add',
                        data: data,
                        contentType: false,
                        processData: false,
                        success: function (data) {
                            if (data.success) {

                                $("#courseid").val(data.data);
                                $('#tab-course,#tab-header-course').removeClass('active');
                                $('#tab-lesson,#tab-header-lesson').addClass('active');

                                ShowMessage(data.message);
                                history.pushState({}, "", "/Course/Add?id=" + data.data);


                            } else {
                                ShowMessageError(data.message);
                            }
                        }
                    });

                }
                return false;

            });

            $("#btnSubmit").click(function () {

                var form = $("#courseForm");
                form.removeData('validator');
                form.removeData('unobtrusiveValidation');
                $.validator.unobtrusive.parse(form);

                if (form.valid()) {

                    var id = $("#courseid").val();

                    $.ajax({
                        type: 'POST',
                        url: '/Course/Publish/'+id,

                        success: function (data) {
                            if (data.success) {
                                ShowMessage(data.message, function () {
                                    window.location.href = "/Course/Index";
                                });


                            } else {
                                ShowMessageError(data.message);
                            }
                        }
                    });
                }
                return false;

            });
        });


        function ShowPopup(url) {
            var modalId = 'modalDefault';
            var modalPlaceholder = $('#' + modalId + ' .modal-dialog .modal-content');

            var new_url = url;

            $.get(new_url)
                .done(function (response) {
                    modalPlaceholder.html(response);
                    popup = $('#' + modalId + '').modal({
                        keyboard: false,
                        backdrop: 'static'
                    });
                }) ;
        }

        function SubmitForm(form, url) {
            $(form).removeData('validator');
            $(form).removeData('unobtrusiveValidation');
            $.validator.unobtrusive.parse(form);
            if ($(form).valid()) {
                //var data = $(form).serializeJSON();
                //data = JSON.stringify(data);
                var data = new FormData(form);
                $.ajax({
                    type: 'POST',
                    url: url,
                    data: data,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data.success) {
                            popup.modal('hide');
                            ShowMessage(data.message);
                            if (table) {
                                table.draw();
                            }

                        } else {
                            ShowMessageError(data.message);
                        }
                    }
                });

            }
            return false;
        }

        function RemoveLesson(id) {


            Swal.fire({
                title: "删除",
                text: "确定删除?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#dd4b39",
                confirmButtonText: "是的，删除!",
                cancelButtonText: "取消",

            }).then(function () {
                $.ajax({
                    type: 'POST',
                    url: '/Course/Lesson/Delete/' + id,
                    success: function (data) {
                        if (data.success) {
                            ShowMessage(data.message);
                            table.draw();
                        } else {
                            ShowMessageError(data.message);
                        }
                    }
                });
            });

        }


    </script>
}
